package com.epam.iunna.bookshop.controller.actions;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.epam.iunna.bookshop.controller.application.Constants;
import com.epam.iunna.bookshop.controller.filters.AuthFilter;
import com.epam.iunna.bookshop.controller.utils.dispatch.ActionInt;
import com.epam.iunna.bookshop.model.User;
import com.epam.iunna.bookshop.model.UserDao;


public class Login implements ActionInt{

	@Override
	public String perform(HttpServletRequest request,
			HttpServletResponse response) {
		String login = request.getParameter("login");
		String password = request.getParameter("password");
		
		Map<String,String> errorMap = new HashMap<String,String>();
		
		if( login !=null && password !=null ){
		    //validation
			if( login.isEmpty() ){
				errorMap.put("login", " * required");
			}
			if( password.isEmpty() ){
				errorMap.put("password", " * required");
			}
			if( !errorMap.isEmpty() ){
			    request.setAttribute("errorMap", errorMap);
			    return "/login.jsp";
			}
			
			//call dao find user by login pass
			UserDao dao = new UserDao();
			User user = null;
			try{
			    user = dao.getByLoginPass(login, password);
			}catch(Exception e){
			    //LOG.error("cannot auth user",this,e);
			    e.printStackTrace();
			    return Constants.FATAL_ERROR_PAGE_PATH;
			}
			if( user != null){
				request.getSession(true).setAttribute( AuthFilter.USER_SESSION_KEY , user);
				BooksList bookListAction = new BooksList();
				return bookListAction.perform(request, response);
			}else{
				errorMap.put("login", " * login or password is incorrect");
				request.setAttribute("errorMap", errorMap);
                return "/login.jsp";
			}
		}
		else{
			return "/login.jsp";
		}
	}

}
